package cn.com.dhc.danlu.fragment;

import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import cn.com.dhc.danlu.R;
import cn.com.dhc.danlu.dlware.OperatorUtils;
import cn.com.dhc.danlu.dlware.net.GeneralBusinessObserver;
import cn.com.dhc.danlu.fragment.base.BaseActivePhoneFragment;
import cn.com.dhc.danlu.fragment.bridge.FragmentBridge;
import cn.com.dhc.danlu.util.CommonUtils;
import cn.com.dhc.danlu.util.ToastUtil;
import cn.com.dhc.danlu.widget.RotateImageView;
import cn.com.dhc.danlu.widget.dialog.ViewDialog;
import cn.com.hd.mall.web.webservices.entity.BaseResponse;
import cn.com.hd.mall.web.webservices.entity.request.account.ActiveNewPhoneRequest;
import cn.com.hd.mall.web.webservices.entity.request.common.GetPicValCodeRequest;
import cn.com.hd.mall.web.webservices.entity.request.common.ValidatePicValCodeRequest;
import cn.com.hd.mall.web.webservices.entity.request.common.ValidateSmsCodeRequest;
import cn.com.hd.mall.web.webservices.entity.request.regist.VerificationCodeRequest;
import cn.com.hd.mall.web.webservices.entity.response.common.GetPicValCodeResponse;

import static cn.com.dhc.danlu.dlware.global.DanluApplication.agent;

/**
 * @author wuhaiyang
 */
public class UnBindOrActiveNewPhoneFragment extends BaseActivePhoneFragment {
    private String mTelphone;
    /**
     * 图形验证码base 64 字符串
     */
    private String mGraphicsBase64Str;
    /**
     * 判断当卡是否是解绑手机号fragment 标志
     */
    private boolean isUnbind = true;
    // private DanluTaskProxy danluTaskProxy;
    private boolean isGetSmsCodeSuc = false;
    private EditText et_graphicscode; // 图形验证码输入框
    private ImageView iv_graphics_validation;
    private RotateImageView iv_refresh; // 图形验证码刷新控件
    private TextView tv_phone_content;

    public static UnBindOrActiveNewPhoneFragment newInstance(String phone, boolean isUnBind) {
        UnBindOrActiveNewPhoneFragment fragment = new UnBindOrActiveNewPhoneFragment();
        Bundle bundle = new Bundle();
        bundle.putString("phone", phone);
        bundle.putBoolean("isUnbind", isUnBind);
        fragment.setArguments(bundle);
        return fragment;
    }

    /**
     * 初始化之后调用
     */
    //    public void setDanluTaskProxy(DanluTaskProxy danluTaskProxy) {
    //        this.danluTaskProxy = danluTaskProxy;
    //    }

    /**
     * 校验短信验证码
     *
     * @param smscode
     *         所输入短信验证码
     */
    private void validateSmsCode(String smscode) {
        if (isUnbind) {
            // 验证手机号
            ValidateSmsCodeRequest request = new ValidateSmsCodeRequest();
            request.setToken(agent.getToken());
            request.setValCode(smscode);
             //add by llq
            agent.getApi().validateMsgValCode(request)
                    .compose(OperatorUtils.defaultSchedulers())
                    .subscribe(new GeneralBusinessObserver<BaseResponse>(getActivity(), R.string.tips_validate_sms_code) {
                        @Override
                        protected void onSuccess(BaseResponse baseResponse) {
                            // 跳转到激活新手机号fragment
                            mBridgeCallback.onHandle(FragmentBridge.TYPE_GO_BIND_NEWPHONE, null);
                            resetVariable();
                        }

                        @Override
                        protected String parseBussinessException(String code) {
                            return getActivity().getString(R.string.wrong_smscode);
                        }

                        @Override
                        protected void onAlertTips(String displayMessage) {
                            ToastUtil.getInstance().show(TextUtils.isEmpty(displayMessage) ? "短信验证码错误！" : displayMessage);
                        }
                    });
        } else {
            activeNewPhone(smscode);
        }
    }

    protected void resetVariable() {

    }

    /**
     * 激活新的手机号（更换手机号时）
     *
     * @param smsCode
     *         短信验证码
     */
    protected void activeNewPhone(String smsCode) {
        ActiveNewPhoneRequest request = new ActiveNewPhoneRequest();
        request.setTel(et_phone.getText().toString().trim());
        request.setToken(agent.getToken());
        request.setValCode(smsCode);
        //add by llq 对应原方法 activePhone（）
        agent.getApi().activeNewPhone(request)
                .compose(OperatorUtils.defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<BaseResponse>(getActivity(), R.string.tips_active_phone) {
                    @Override
                    protected void onSuccess(BaseResponse baseResponse) {
                        showActiveNewPhoneSucDialog(); // 新手机号激活成功
                    }

                    @Override
                    protected String parseBussinessException(String code) {
                        String displayMsg = "";
                        switch (code) {
                            case "1":
                                displayMsg = getActivity().getString(R.string.tips_activate_failed);
                                break;
                            case "2":
                                displayMsg = getActivity().getString(R.string.tips_phone_num_occupied);
                                break;
                            case "3":
                                displayMsg = getActivity().getString(R.string.tips_wrong_identifying_code);
                                break;
                            case "5":
                                displayMsg = getActivity().getString(R.string.tips_active_failed_unknow);
                                break;
                            default:
                                displayMsg = getActivity().getString(R.string.tips_activate_failed);
                                break;
                        }
                        return displayMsg;
                    }

                    @Override
                    protected void onAlertTips(String displayMessage) {
                        ToastUtil.getInstance().show(TextUtils.isEmpty(displayMessage) ? "激活失败！" : displayMessage);
                    }
                });
    }

    /**
     * 弹出激活新手机号成功对话框
     */
    protected void showActiveNewPhoneSucDialog() {
        new ViewDialog.Builder(getActivity())
                .setMessage("更换成功，新手机号" + et_phone.getText().toString().trim() + "" + "。您可以使用新手机号登录或者找回密码。")
                .setCancelable(false).setPositiveButton(R.string.btn_confirm, new OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                mBridgeCallback.onHandle(FragmentBridge.TYPE_ACTIVE_NEWPHONE_SUC, null);
            }
        }).create().show();
    }

    /**
     * 点击获取短信验证码交互逻辑
     */
    private void checkLogic() {
        if (isUnbind) {
            // 解除绑定原来的手机号
            if (judgeIsInputGraphicsCode()) {
                String etGraphicsCode = et_graphicscode.getText().toString().trim();
                validatePicCodeRequest(etGraphicsCode, mTelphone);
            }
        } else {
            // 激活新手机号码
            String newPhone = et_phone.getText().toString().trim();
            if (TextUtils.isEmpty(newPhone)) {
                ToastUtil.getInstance().show("请输入新的手机号码");
                return;
            }
            if (!CommonUtils.isMobileNumber(newPhone)) {
                ToastUtil.getInstance().show(R.string.register_tel_msg);
                return;
            }
            if (judgeIsInputGraphicsCode()) { // 校验图形验证码
                validatePicCodeRequest(et_graphicscode.getText().toString().trim(), et_phone.getText().toString().trim());
            }
        }
    }

    /**
     * 请求webservice校验图形验证码
     *
     * @param etGraphicsCode
     *         所输入图形验证码
     * @param phone
     *         电话号码
     */
    private void validatePicCodeRequest(String etGraphicsCode, final String phone) {
        ValidatePicValCodeRequest request = new ValidatePicValCodeRequest();
        request.setToken(agent.getToken());
        request.setPicValCode(etGraphicsCode);
        //add by llq
        agent.getApi().validatePicValCode(request)
                .compose(OperatorUtils.defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<BaseResponse>(getActivity(), R.string.tips_validate_pic_code) {
                    @Override
                    protected void onSuccess(BaseResponse baseResponse) {
                        handleSubsquentAction(phone); // 校验成功开始请求获取
                    }

                    @Override
                    protected String parseBussinessException(String code) {
                        // 重新刷新图形验证码 清空 输入框的图形验证码
                        getGraphicsImgBaseStr();
                        et_graphicscode.getText().clear();
                        return getActivity().getString(R.string.tips_wrong_pic_code);
                    }

                    @Override
                    protected void onAlertTips(String displayMessage) {
                        ToastUtil.getInstance().show(TextUtils.isEmpty(displayMessage) ? "图形验证码错误！" : displayMessage);
                    }
                });
    }

    /**
     * 图形验证码成功后 后续操作 根据isUnbind 处理不同逻辑
     */
    protected void handleSubsquentAction(String phone) {
        // 开始计时
        //        startTimer ();
        VerificationCodeRequest request = new VerificationCodeRequest();
        request.setToken(agent.getToken());
        request.setTel(phone);
        //add by llq
        if (isUnbind) {  // 解绑手机
            agent.getApi().getSmsCodeUnbindPhone(request)
                    .compose(OperatorUtils.defaultSchedulers())
                    .subscribe(new GeneralBusinessObserver<BaseResponse>(getActivity(), R.string.tips_get_sms_code) {
                        @Override
                        protected void onSuccess(BaseResponse baseResponse) {
                            showToast("验证码已发送");
                            isGetSmsCodeSuc = true;
                            startTimer();
                        }

                        @Override
                        protected String parseBussinessException(String code) {
                            isGetSmsCodeSuc = false;
                            String dispalyMsg = "";
                            switch (code) {
                                case "1":
                                    dispalyMsg = getActivity().getString(R.string.tips_wrong_phone_num_format);
                                    reGetSmsCode();
                                    break;
                                case "2":
                                    dispalyMsg = getActivity().getString(R.string.interval_lessthan);
                                    break;
                                case "3":
                                    dispalyMsg = getActivity().getString(R.string.send_sms_error);
                                    reGetSmsCode();
                                    break;
                                case "4":
                                    dispalyMsg = getActivity().getString(R.string.send_sms_error);
                                    reGetSmsCode();
                                    break;
                                case "5":
                                    dispalyMsg = getActivity().getString(R.string.tips_phone_num_exist);
                                    reGetSmsCode();
                                    break;
                                default:
                                    break;

                            }
                            return dispalyMsg;
                        }

                        @Override
                        protected void onAlertTips(String displayMessage) {
                            ToastUtil.getInstance().show(TextUtils.isEmpty(displayMessage) ? "解绑短信验证码获取失败！" : displayMessage);
                        }
                    });
        } else {
            // 获取绑定手机短信验证码
            agent.getApi().getSmsCodeBindPhone(request)
                    .compose(OperatorUtils.defaultSchedulers())
                    .subscribe(new GeneralBusinessObserver<BaseResponse>(getActivity(), R.string.tips_get_sms_code) {
                        @Override
                        protected void onSuccess(BaseResponse baseResponse) {
                            showToast("验证码已发送");
                            isGetSmsCodeSuc = true;
                            startTimer();
                        }

                        @Override
                        protected String parseBussinessException(String code) {
                            isGetSmsCodeSuc = false;
                            String dispalyMsg = "";
                            switch (code) {
                                case "1":
                                    dispalyMsg = getActivity().getString(R.string.tips_wrong_phone_num_format);
                                    reGetSmsCode();
                                    break;
                                case "2":
                                    dispalyMsg = getActivity().getString(R.string.interval_lessthan);
                                    break;
                                case "3":
                                    dispalyMsg = getActivity().getString(R.string.tips_not_unbind);
                                    break;
                                case "4":
                                    dispalyMsg = getActivity().getString(R.string.send_sms_error);
                                    reGetSmsCode();
                                    break;
                                case "5":
                                    dispalyMsg = getActivity().getString(R.string.tips_phone_num_exist);
                                    reGetSmsCode();
                                    break;
                                default:
                                    break;
                            }
                            return dispalyMsg;
                        }

                        @Override
                        protected void onAlertTips(String displayMessage) {
                            ToastUtil.getInstance().show(TextUtils.isEmpty(displayMessage) ? "绑定短信验证码获取失败！" : displayMessage);
                        }
                    });

        }
    }

    private boolean judgeIsInputGraphicsCode() {
        String etGraphicsCode = et_graphicscode.getText().toString().trim();
        if (TextUtils.isEmpty(mGraphicsBase64Str)) {
            ToastUtil.getInstance().show("请先获取图形验证码");
            return false;
        }
        if (TextUtils.isEmpty(etGraphicsCode)) {
            ToastUtil.getInstance().show("请先输入图形验证码");
            return false;
        }
        return true;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
        if (getArguments() != null) {
            // 获取手机号码
            mTelphone = getArguments().getString("phone");
            isUnbind = getArguments().getBoolean("isUnbind");
        }
        if (isUnbind) {
            // 解绑原手机号
            et_phone.setVisibility(View.GONE);
            tv_phone_content.setText(String.format(getResources().getString(R.string.input_smscode), mTelphone));
        } else {
            // 激活新的手机号
            et_phone.setVisibility(View.VISIBLE);
            tv_phone_content.setText(getResources().getString(R.string.input_new_phone_tips));
        }
        getGraphicsImgBaseStr();
    }

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.dl_fragment_unbind_active, container, false);
    }

    /**
     * 重写父类onClick方法
     */
    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.iv_refresh: // 刷新图形验证码
                getGraphicsImgBaseStr();
                break;

            case R.id.btn_getcode: // 获取验证码
                checkLogic();
                break;

            case R.id.btn_verify: // 确定按钮
                if (isUnbind) {
                    // 解绑原手机号码
                    if (!judgeIsInputGraphicsCode()) {
                        return;
                    }
                    if (!isGetSmsCodeSuc) {
                        showToast("请先获取短信验证码");
                        return;
                    }
                    if (TextUtils.isEmpty(et_code.getText().toString().trim())) {
                        showToast("请输入短信验证码");
                        return;
                    }
                    // 校验短信验证码
                    validateSmsCode(et_code.getText().toString().trim());
                } else {
                    // 校验短信验证码（激活新的手机号码）
                    validateSmsCode(et_code.getText().toString().trim());
                }
                break;

            default:
                break;
        }
    }

    /**
     * 请求获取验证码 图片
     */
    private void getGraphicsImgBaseStr() {
        if (iv_refresh.isRotate()) {
            return;
        }

        iv_refresh.start(RotateImageView.CLOCKWISE);
        GetPicValCodeRequest request = new GetPicValCodeRequest();
        request.setToken(agent.getToken());
        //add by llq
        agent.getApi().getPicValCode(request)
                .compose(OperatorUtils.<GetPicValCodeResponse>defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<GetPicValCodeResponse>() {
                    @Override
                    protected void onSuccess(GetPicValCodeResponse getPicValCodeResponse) {
                        iv_refresh.stop();
                        mGraphicsBase64Str = getPicValCodeResponse.getPicValCode();  // 图形验证码base 64 字符串
                        iv_graphics_validation.setImageBitmap(CommonUtils.base64ToBitmap(mGraphicsBase64Str)); // 设置图形验证码图片
                    }

                    @Override
                    protected String parseBussinessException(String code) {
                        iv_refresh.stop();
                        return getActivity().getString(R.string.tips_get_pic_code_abnormal);
                    }

                    @Override
                    protected void onAlertTips(String displayMessage) {
                        iv_refresh.stop();
                        ToastUtil.getInstance().show(TextUtils.isEmpty(displayMessage) ? "图形验证码获取失败！" : displayMessage);
                    }
                });
    }

    private void showToast(String msg) {
        ToastUtil.getInstance().show(msg);
    }

    private void initView(View view) {
        et_graphicscode = (EditText) view.findViewById(R.id.et_graphicscode);
        iv_graphics_validation = (ImageView) view.findViewById(R.id.iv_graphics_validation);
        iv_refresh = (RotateImageView) view.findViewById(R.id.iv_refresh);
        tv_phone_content = (TextView) view.findViewById(R.id.tv_phone_content);
        iv_refresh.setOnClickListener(this);
    }
}
